package com.zyzd.baseretrofit.base.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.zyzd.baseretrofit.R;
import com.zyzd.baseretrofit.base.adapter.BaseRecyclerAdapter;
import com.zyzd.baseretrofit.bean.remote.ApiResultBean;
import com.zyzd.baseretrofit.widget.recycler.RecyclerRefreshLayout;
import com.zyzd.commontools.log.TLog;

import java.util.ArrayList;
import java.util.Date;

import butterknife.Bind;
import rx.Observable;

/**
 * Created by 李宗源 on 2016/8/3.
 */
public abstract class BaseRecyclerViewFragment<T> extends BaseNetFragment<ArrayList<T>> implements BaseRecyclerAdapter.OnItemClickListener, RecyclerRefreshLayout.SuperRefreshLayoutListener {

    protected static int initPageIndex = 0;
    @Bind(R.id.rl_title)
    public FrameLayout mRlTitleBar;
    @Bind(R.id.recyclerView)
    public RecyclerView mRecyclerView;
    @Bind(R.id.refreshLayout)
    public RecyclerRefreshLayout mRefreshLayout;
    @Bind(R.id.iv_bg)
    public ImageView mIvBg;
    public int nextPageIndex;
    public BaseRecyclerAdapter<T> mAdapter;
    protected boolean mIsRefresh;
    protected long stampTime;
    protected boolean hasMore;
    protected ArrayList<T> mList;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recycler_view;
    }

    @Override
    public void initData() {
        mRecyclerView.setLayoutManager(getLayoutManager());//设置布局管理器，默认垂直线性
        mAdapter = getRecyclerAdapter();//获取adapter
        mAdapter.setState(BaseRecyclerAdapter.STATE_HIDE, false);
        mRecyclerView.setAdapter(mAdapter);//设置adapter
        mAdapter.setOnItemClickListener(this);//设置条目点击事件
        mRefreshLayout.setSuperRefreshLayoutListener(this);//设置下拉刷新和加载更多的监听
        mRefreshLayout.setColorSchemeResources(
                R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);

        mList = new ArrayList<>();
        if (isAutoLoad()) {
            mRefreshLayout.setRefreshing(true);//主动刷新，走下拉刷新逻辑
            onRefreshing();
        }
    }

    /**
     * 设置适配器
     */
    protected abstract BaseRecyclerAdapter<T> getRecyclerAdapter();

    /**
     * 设置布局管理器
     */
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(getActivity());
    }


    @Override
    protected void parseData(ArrayList data) {
        TLog.d("zyzd", "BaseRecyclerViewFragment>>parseData--> " + data.toString());
        mList = data;
        nextPageIndex++;//请求成功后，修改下一页

        if (mIsRefresh) {//主动刷新
            mAdapter.clear();
            mAdapter.addAll(data);
            mRefreshLayout.setCanLoadMore(true);
            TLog.d("zyzd", getSimpleName() + ">>parseData--> " + "refresh");
        } else {
            mAdapter.addAll(data);
            TLog.d("zyzd", getSimpleName() + ">>parseData--> " + "loadMore");
        }

        if (data.size() < getPageSize()) {
            hasMore = false;
            mAdapter.setState(BaseRecyclerAdapter.STATE_NO_MORE, true);
        }
    }

    /**
     * @return 每页返回数据数量, 根据需求进行调整
     */
    protected int getPageSize() {
        return 10;
    }

    @Override
    public void onItemClick(int position, long itemId) {
        TLog.d("zyzd", getSimpleName() + ">>onItemClick--> " + mAdapter.getItem(position).toString());
    }

    /**
     * 刷新
     */
    @Override
    public void onRefreshing() {
        TLog.d("zyzd", getSimpleName() + ">>onRefreshing");
        mIsRefresh = true;//true 表示主动刷新
        stampTime = (new Date()).getTime();
        nextPageIndex = initPageIndex;
        hasMore = true;
        requestData();
    }

    /**
     * 请求数据
     */
    protected void requestData() {
        toSubscribe(getObservable(mIsRefresh), getSubscriber());
    }

    protected abstract Observable<ApiResultBean<ArrayList<T>>> getObservable(boolean isRefresh);

    /**
     * 获取请求路径
     *
     * @param isRefresh
     * @return
     */
    protected abstract String getUrl(boolean isRefresh);

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        TLog.d("zyzd", "onLoadMore执行了");
        if (hasMore) {
            mAdapter.setState(BaseRecyclerAdapter.STATE_LOAD_MORE, true);
            requestData();
        } else {//避免出现当没有更多数据时，导致下拉刷新失效
            onComplete(getSimpleName());
        }
    }

    /**
     * 请求完成（无论成功还是失败）
     */
    @Override
    protected void onRequestFinish(String tag) {
        onComplete(tag);
    }

    /**
     * 完成
     */
    protected void onComplete(String tag) {
        if (tag.equals(getSimpleName())) {
            mRefreshLayout.onComplete();
            mIsRefresh = false;
        }
    }

    @SuppressWarnings("EmptyMethod")
    @Override
    public void setListener() {

    }

    /**
     * 是否首次自动加载
     *
     * @return
     */
    protected boolean isAutoLoad() {
        return true;
    }

    @Override
    public void onClick(View v) {

    }
}
